package com.slkj.shilixiaoyuanapp.ui.parent.tool.leave;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.example.api.InjectParam;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.data.LeaveTypeData;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.BasePickerTypeEntity;
import com.slkj.shilixiaoyuanapp.entity.PeopleEntity;
import com.slkj.shilixiaoyuanapp.entity.UserEntity;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.entity.parent.AskLeaveRecordEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChosePeopleActivity;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.TestDataProvider;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.PickerViewProvider;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;
import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SPR_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.NO_CHOSE;

@ActivityInfo(layout = R.layout.activity_leave_wtg1, title = "未通过")
@RuntimePermissions
public class LeaveWtgActivity extends BaseActivity {
    @InjectParam
    int id;
    @InjectParam
    AskLeaveRecordEntity data;
    @BindView(R.id.recyc_pic)
    RecyclerView recycerPic;
    ArrayList<String> picPaths = new ArrayList<>();
    ChosePicAdapter adapter;
    public TakePictureUtils takePictureUtils;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.edit_day)
    TextView editDay;
    @BindView(R.id.edit_content)
    NumberEditText editContent;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_remark)
    TextView tvWtg;
    List<Integer> sqrIds = new ArrayList<>();
    private ArrayList<PeopleEntity> peopleEntities = new ArrayList<>();
    private String startTime, endTime;
    private int qjTypeId = NO_CHOSE;
    public static final String tag = "LeaveWtgActivity";
    //班级班级
    private int classId = NO_CHOSE;
    //学生id
    private int studentId = NO_CHOSE;
    String img;
    String body;
    float day;

    @Override
    protected void init() {
        LeaveWtgActivity__JumpCenter.bind(this);
        RxEventProcessor.get().bind(this);
        tvUserName.setText(data.getName());
        if (data.getType()==1){
            tvType.setText("事假");
        }else {
            tvType.setText("病假");
        }
        tvStartTime.setText(data.getStartDate());
        tvEndTime.setText(data.getEndDate());
        editDay.setText(String.valueOf(data.getDuration()));
        editContent.setText(data.getBody());
        tvWtg.setText(data.getRefute());
        recycerPic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        if (data.getImg() != null && !data.getImg().isEmpty()) {
            picPaths.addAll(data.getImg());
        }
        adapter = new ChosePicAdapter(picPaths, this,true);
        recycerPic.setAdapter(adapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });

        //sqrIds = ChosePeopleActivity.getIdList(data.getAuditor());
        startTime = data.getStartDate();
        endTime = data.getEndDate();
        qjTypeId = data.getType();
        for (int i=0;i<UserRequest.getInstance().getUser().getStudents().size();i++){
            if (UserRequest.getInstance().getUser().getStudents().get(i).getName().equals(data.getName())){
                studentId=UserRequest.getInstance().getUser().getStudents().get(i).getId();
                classId=UserRequest.getInstance().getUser().getStudents().get(i).getClassId();
            }
        }
        day= (float) data.getDuration();
        img=StringUtils.listToString(data.getImg());
        body=data.getBody();
    }


    @OnClick(R.id.tv_up)
    void upData() {
        if (studentId == NO_CHOSE) {
            showToast("请选择学生");
            return;
        }
        if (qjTypeId == NO_CHOSE) {
            showToast("请选择请假类型");
            return;
        }

        if (TextUtils.isEmpty(startTime)) {
            showToast("请选择开始时间");
            return;
        }
        if (TextUtils.isEmpty(endTime)) {
            showToast("请选择结束时间");
            return;
        }
        String context = editContent.getText();
        if (TextUtils.isEmpty(context)) {
            showToast("请输入请假事由");
            return;
        }
        //String day=editDay.getText().toString();
        /**
         * 遍历图片获取真实地址
         *
         */
        Observable.just(picPaths)
                .flatMap(picPaths -> {
                    List<String> newPath = new ArrayList<>();
                    for (String path : picPaths) {
                        File file = null;
                        try {
                            file = Glide.with(LeaveWtgActivity.this)
                                    .load(path)
                                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                    .get();
                            newPath.add(file.getPath());
                        } catch (Exception ex) {
                            newPath.add(path);
                        }
                    }
                    return UpdataFileUtil.UpImgObservable("award", newPath);
                })
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        img = StringUtils.listToString(result);
                        body=editContent.getText();
                        day= Float.parseFloat(editDay.getText().toString());
                        return HttpHeper.get().parentService().studentAskforLeave(studentId,classId,qjTypeId, startTime, endTime, day,img,body);
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true, this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(LeaveWtgActivity.this,data);
                    }
                });
    }

    @OnClick(R.id.layout_chose_pic)
    void chosePic() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW) {
            showToast("最多添加" + CHOSE_PIC_MAX_SIZW + "张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                LeaveWtgActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(LeaveWtgActivity.this);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LeaveWtgActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }

//    /**
//     * 选择学生
//     */
//    @OnClick(R.id.layout_chose_student)
//    public void onLayoutChooseStudent() {
//        List<UserEntity.StudentEntity> students = UserRequest.getInstance().getUser().getStudents();
//        PickerViewProvider.getCommonPicker(this, students, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                tvUserName.setText(students.get(options1).getName());
//                studentId = students.get(options1).getId();
//                classId  = students.get(options1).getClassId();
//            }
//        }).show();
//    }


    @OnClick(R.id.layout_chose_type)
    public void onLayoutChoseTypeClicked() {
        List<BasePickerTypeEntity> typeEntityList = LeaveTypeData.getInstance().getTypeEntityList();
        PickerViewProvider.getCommonPicker(this, typeEntityList, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvType.setText(typeEntityList.get(options1).getName());
                qjTypeId = options1 + 1;
            }
        }).show();
    }

    @OnClick(R.id.layout_chose_start_time)
    public void onLayoutChoseStartTimeClicked() {
        PickerViewProvider.getTimePicker(this, (date, v) -> {
            startTime = TimeUtils.dateToStrM(date);
            tvStartTime.setText(startTime);
        }).show();
    }

    @OnClick(R.id.layout_chose_end_time)
    public void onLayoutChoseEndTimeClicked() {
        PickerViewProvider.getTimePicker(this, (date, v) -> {
            endTime = TimeUtils.dateToStrM(date);
            tvEndTime.setText(endTime);
        }).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }
}
